﻿$(function () {
    $('#tablist2').tabs({
        onBeforeClose: function (title, index) {
            var entity = ko.contextFor($('#tablist2').tabs('getTab', index)[0]).$data;
            if (entity.state() == 'Modified') {
                var r = confirm("You has modified content.Do you want to save before close?");
                if (r == true) {
                    manager.saveChanges([entity]).then(function (data) {
                        alert('Save ' + entity.Title() + ' successful.');
                    }).fail(function (e) {
                        alert(e);
                    });
                }
                else {
                    ////Remove entity CategoryAnswer that un-used: cascahe delete
                    var length = entity.CategoryAnswers().length;
                    for (var i = 0; i < length; i++) {
                        entity.CategoryAnswers()[0].entityAspect.setDetached();
                    }
                    entity.entityAspect.setDetached();
                    entity.state('Unchanged');
                }
            }
        },
        onClose: function (title, index) {
            for (var i = 0; i < viewModel.answersdetail().length; i++) {
                if (title == viewModel.answersdetail()[i].text) {
                    viewModel.answersdetail.splice(index, 1);
                }
            }
            
        }
    });
    $('#aa').tree({
        onDblClick: function (node) {
            manager.fetchEntityByKey("CompetencyAnswer", node.id).then(function (result) {
                var entity = result.entity;
                if (!checkExisttab(entity)) {
                entity.state = ko.observable('Unchanged');                
                entity.categories = viewModel.categories;
                entity.selectedcategory = ko.observableArray();

                    //Category binding
                for (var i = 0; i < entity.CategoryAnswers().length; i++) {
                    entity.selectedcategory.push(entity.CategoryAnswers()[i].CategoryId());
                }
                //Question binding
                for (var i = 0; i < entity.QuestionAnswers().length; i++) {
                    entity.QuestionAnswers()[i].Title = entity.QuestionAnswers()[i].Question().Title();
                }
                //Observe changes               
                entityFunction4A(entity, node);

                viewModel.answersdetail.push(entity);
                var newtab = $('#tabans').clone();
                $('#tablist2').tabs('add', {
                    title: entity.Title(),
                    content: newtab.html(),
                    closable: true,
                    tools: [{
                        iconCls: 'icon-save',
                        handler: function () {
                            if (manager.hasChanges()) {
                                manager.saveChanges([entity]).then(function (data) {
                                    alert('Save ' + entity.Title() + ' successful.');
                                }).fail(function (e) {
                                    alert(e);
                                });;
                            } else {
                                alert('Nothing to save');
                            }
                        }
                    }]
                });
                var obj = $('#tablist2').tabs('getTab', $('#tablist2').tabs('tabs').length - 1);
                ko.applyBindings(entity, obj[0]);
                    ////Remove duplicate tag (bug: combotree) and change div id:questionContent to table id
                if (obj.find('.combo')[1] != undefined) {
                    obj.find('.combo')[1].remove();
                }
                    
                }



            }).fail(function (e) {
                alert(e);
            });

        }

    });

});
function checkExisttab(entity) {
    for (var i = 0 ; i < $('#tablist2').tabs('tabs').length; i++) {
        var name = $('#tablist2').tabs('getTab', i).panel('options').title;
        if (name == entity.Title()) {
            return true;
        }
    }
    return false;
}
function entityFunction4A(entity, node) {
    entity.QuestionAnswers.subscribe(function (changes) {
        changes.forEach(function (change) {
            if (change.status === 'added') {
                //change.value.Title = change.value.Question().Title();
                change.value.Title = $('#qq').tree('getSelected').text;
            }
            entity.state('Modified');
        });
    }, null, "arrayChange");
    entity.selectedcategory.subscribe(function (changes) {
        changes.forEach(function (change) {
            if (change.status === 'added') {
                var ent = createCategoryAnswers(node.id, change.value, entity);
            }
            if (change.status === 'deleted') {
                removeCategoryA(node.id, change.value);
            }
            entity.state('Modified');
        });
    }, null, "arrayChange");
    entity.removeQuestion = function () {
        var rowindex = $('#tablist2').tabs('getSelected').find('#dd')[0].selectedIndex;
        var tabindex = $('#tablist2').tabs('getTabIndex', $('#tablist2').tabs('getSelected'));
        viewModel.answersdetail()[tabindex].QuestionAnswers()[rowindex].entityAspect.setDeleted();
        entity.state('Modified');
    }
    entity.entityAspect.propertyChanged.subscribe(function (changes) {
        entity.state('Modified');
    }, null, "arrayChange");
}

viewModel.addAnswer = function () {
    var newtab = $('#tabans').clone();
    var en = {
        Title: ko.observable(''),
        Text: ko.observable(''),
        Feedback: ko.observable(''),
        categories: viewModel.categories,
        selectedcategory: ko.observableArray(),
        QuestionAnswers: ko.observableArray(),
        removeQuestion: function () {
            var rowindex = $('#tablist2').tabs('getSelected').find('#dd')[0].selectedIndex;
            en.QuestionAnswers.splice(rowindex, 1);
        }
    }

    $('#tablist2').tabs('add', {
        title: 'New answer', //Do not edit this title
        content: newtab.html(),
        closable: true,
        tools: [{
            iconCls: 'icon-save',
            handler: function () {
                var needadd = []; //Array of entity
                var newAnswer = manager.createEntity('CompetencyAnswer', { Title: en.Title(), Text: en.Text(), Feedback: en.Feedback() });
                //Add list of categories
                for (var i = 0; i < en.selectedcategory().length; i++) {
                    var QA = manager.createEntity('CategoryAnswer', { AnswerId: newAnswer.Id(), CategoryId: en.selectedcategory()[i] });
                    newAnswer.CategoryAnswers.push(QA);
                    needadd.push(QA);
                }
                //Add list of answers
                for (var i = 0; i < en.QuestionAnswers().length; i++) {
                    var QA = manager.createEntity('QuestionAnswer', { QuestionId: en.QuestionAnswers()[i].QuestionId, AnswerId: newAnswer.Id() });
                    newAnswer.QuestionAnswers.push(QA);
                    needadd.push(QA);
                }
                manager.addEntity(newAnswer);
                needadd.unshift(newAnswer);
                manager.saveChanges(needadd).then(function (data) {
                    alert('Save ' + en.Title() + ' successful.');
                });
            }
        }]
    });
    var obj = $('#tablist2').tabs('getTab', $('#tablist2').tabs('tabs').length - 1);
    ko.applyBindings(en, obj[0]);
}
viewModel.copyAnswer = function () {
    var node = $('#aa').tree('getSelected');
    var index = $('#tablist').tabs('getTabIndex', $('#tablist').tabs('getSelected'));
    var model = ko.contextFor($('#tablist').tabs('getTab', index)[0]).$data;
    if(node != null){
        var check = true; var valid = true;
        for (var i = 0; i < model.QuestionAnswers().length; i++) {
            if (model.QuestionAnswers()[i].AnswerId() == node.id) {
                check = false; break;          
            }
        }
        if(check){
            var deletedCat = manager.getEntities('QuestionAnswer', breeze.EntityState.Deleted);
            for (var i = 0; i < deletedCat.length; i++) {
                if (node.id == deletedCat[i].AnswerId()) {
                    deletedCat[i].entityAspect.rejectChanges();
                    model.QuestionAnswers().push(deletedCat[0]);
                    valid = false;
                }
            }    
        }
        if(check && valid){
            if ($('#tablist').tabs('getTab', i).panel('options').title != 'New question') {
                var newobj = createQuestionAnswers(model.Id(), node.id, node.text);
            }else{
                var obj = new Object();
                obj.Title = node.text;
                obj.AnswerId = node.id;
                model.QuestionAnswers.push(obj);
            }
            model.state('Modified');
            
        }
    }
    

}

function createCategoryAnswers(AnswerId, CategoryId, entity) {
    var deletedCat = manager.getEntities('CategoryAnswer', breeze.EntityState.Deleted);
    var check = true;
    for (var i = 0; i < deletedCat.length; i++) {
        if (CategoryId == deletedCat[i].CategoryId()) {
            deletedCat[i].entityAspect.rejectChanges();
            entity.CategoryAnswers().push(deletedCat[0]);
            check = false;
        }
    }
    if (check) {
        var CategoryAnswer = manager.createEntity('CategoryAnswer', { AnswerId: AnswerId, CategoryId: CategoryId });
    }
}
function removeCategoryA(AnswerId, CategoryId) {
    for (var i = 0; i < viewModel.answersdetail.CategoryAnswers().length; i++) {
        var item = viewModel.answersdetail.CategoryAnswers()[i];
        if (item.CategoryId() == CategoryId && item.AnswerId() == AnswerId) {
            if (item.entityAspect.entityState.name == 'Added') {
                item.entityAspect.setDetached();
            } else {
                item.entityAspect.setDeleted();
            }
        }
    }
}